import './prototype'

import {printLog} from "../env";

let tool = {};
/**
 * @description 延迟函数
 * */
tool.delay = (function () {
    let timer = 0;
    return function (callback, time) {
        clearTimeout(timer);
        timer = setTimeout(callback, time);
    };
})();
/**
 * @param {Object} param
 * @description 定时器
 * */
tool.timer = function (param) {
    let data = {
        toDo: param.toDo || function () {
        },
        didStop: param.didStop || function () {
        },
        interval: param.interval || 1000,
        repeats: param.repeats || true
    };
    let timer_t = null;
    let count = 1;
    let obj = {
        clear: function () {
            clearInterval(timer_t);
            data.didStop();
        }
    };
    timer_t = setInterval(function () {
        if (data.repeats) {
            data.toDo(obj);
        } else {
            if (count > 0) {
                count--;
                data.toDo(obj);
            } else {
                clearInterval(timer_t);
                timer_t = null;
                data.didStop();
            }
        }
    }, data.interval);
    return timer_t;
};
/*
 * @param {Object} obj
 * @description 克隆一个对象
 * */
tool.clone = function (obj) {
    // Handle the 3 simple types, and null or undefined
    if (null === obj || "object" !== typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        let copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        let copy = [];
        for (let i = 0, len = obj.length; i < len; ++i) {
            copy[i] = Object.assign({}, obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        return Object.assign({}, obj);
    }
    console.warn("Unable to copy obj! Its type isn't supported.");
    throw new Error("Unable to copy obj! Its type isn't supported.");
};
/**description 自定义打印日志*/
tool.log = function (...type) {
    if (printLog) {
        type.forEach(v => {
            if (typeof(v) === 'object') {
                console.log(v);
            } else {
                console.log('%c' + v, 'color:#666699;');
            }
        })
    }
};
/**
 * @param {String} par
 * @param {String} specialKey
 * @description  从URL上获得参数
 */
tool.getPar = function (par, specialKey) {
    //获取当前URL
    let local_url = document.location.href;
    local_url = decodeURI(local_url);
    //获取要取得的get参数位置
    let get = local_url.indexOf(par + "=");
    if (get === -1) {
        return "";
    }
    //截取字符串
    let get_par = local_url.slice(par.length + get + 1);

    //判断特殊par eg:specialKey = toUrl
    if (par === specialKey) {
        return get_par;
    }

    //判断截取后的字符串是否还有其他get参数
    let nextPar = get_par.indexOf("&");
    if (nextPar !== -1) {
        get_par = get_par.slice(0, nextPar);
    }
    return get_par;
};
/**
 * @param {String} name
 * @param {String} value
 * @param {String} time
 * @description 设置cookie   eg:time='d30|s30|h24'
 * */
tool.setCookie = function (name, value, time) {
    let strsec = getsec(time);
    let exp = new Date();
    exp.setTime(exp.getTime() + strsec * 1);
    document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();

    function getsec(str) {
        let str1 = str.substring(1, str.length) * 1;
        let str2 = str.substring(0, 1);
        if (str2 === "s") {
            return str1 * 1000;
        } else if (str2 === "h") {
            return str1 * 60 * 60 * 1000;
        } else if (str2 === "d") {
            return str1 * 24 * 60 * 60 * 1000;
        }
    }
};
/**
 * @param {String} name
 * @description 删除指定cookie
 * */
tool.delCookie = function (name) {
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let cval = tool.getCookie(name);
    if (cval !== null)
        document.cookie = name + "=" + cval + ";path=/;expires=" + exp.toGMTString();
};
/**
 * @param {String} name
 * @description 得到指定cookie
 * */
tool.getCookie = function (name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
};
tool.getDateTime = function () {
    let tNowTime = new Date();
    let myYear = ';' + tNowTime.getFullYear() + ';';
    let myMonth = ';' + (tNowTime.getMonth() - 1 + 1 + 1) + ';';
    let myDay = ';' + tNowTime.getDate() + ';';
    let myHour = ';' + tNowTime.getHours() + ';';
    let myMinu = ';' + tNowTime.getMinutes() + ';';
    let mySecond = ';' + tNowTime.getSeconds() + ';';

    if (myMonth.length < 4) myMonth = '0' + myMonth;
    if (myDay.length < 4) myDay = '0' + myDay;
    if (myHour.length < 4) myHour = '0' + myHour;
    if (myMinu.length < 4) myMinu = '0' + myMinu;
    if (mySecond.length < 4) mySecond = '0' + mySecond;

    let cNewTimeStr;
    cNewTimeStr = myYear + myMonth + myDay + myHour + myMinu + mySecond;
    cNewTimeStr = cNewTimeStr.replace(/;/g, "");
    return cNewTimeStr;
};
/**
 * @param {String} objName
 * @param {String} objValue
 * @param {String} time
 * @description 设置字符串类型的本地缓存
 * */
tool.setStorage = function (objName, objValue, time) {
    time = time || 'd180';
    let strsec = getsec(time);
    let nowTime = tool.getDateTime() - 0;
    let setTime = nowTime + strsec / 1000;
    let obj = {};
    obj['maxage'] = setTime;
    obj['value'] = objValue;

    function getsec(str) {
        let str1 = str.substring(1, str.length) * 1;
        let str2 = str.substring(0, 1);
        if (str2 === "s") {
            return str1 * 1000;
        } else if (str2 === "h") {
            return str1 * 60 * 60 * 1000;
        } else if (str2 === "d") {
            return str1 * 24 * 60 * 60 * 1000;
        }
    }

    let sto = window.localStorage;
    if (sto)
        sto.setItem(objName, JSON.stringify(obj));
};
/**
 * @param {String} objName
 * @description 读取字符串类型的本地缓存
 * */
tool.getStorage = function (objName) {
    let sto = window.localStorage;
    let resu = '';
    if (sto) {
        let ret = JSON.parse(sto.getItem(objName));
        if (ret) {
            let maxage = ret['maxage'] - 0;
            let nowTime = tool.getDateTime() - 0;
            if (maxage - nowTime >= 0) {
                resu = ret['value'];
            } else {
                tool.clearStorage(objName);
            }
        }
    }
    return resu;
};
/**
 * @param {String} objName
 * @description 清除本地缓存，如没指定名称则为清空所有缓存
 * */
tool.clearStorage = function (objName) {
    let sto = window.localStorage;
    if (sto) {
        if (objName)
            sto.removeItem(objName);
        else
            sto.clear();
    }
};
/**
 * @param {String} objName
 * @param {Object} json
 * @param {String} time
 * @description 设置Json类型的本地缓存
 * */
tool.setStorJson = function (objName, json, time) {
    if (json) tool.setStorage(objName, JSON.stringify(json), time);
};
/**
 * @param {String} objName
 * @description 读取Json类型的本地缓存
 * */
tool.getStorJson = function (objName) {
    let ret = null;
    let str = tool.getStorage(objName);
    if (str)
        ret = JSON.parse(str);
    return ret;
};
/**
 * @param {String} str
 * @description 得到原生dom
 * */
tool.navDom = function (str) {
    return document.querySelectorAll(str);
};
/**
 * @param {String} str
 * @param {Function} callback
 * @description 遍历dom 回调中为原生dom
 * */
tool.navDomEach = function (str, callback) {
    let doms = document.querySelectorAll(str);
    for (let i = 0; i < doms.length; i++) {
        if (callback) {
            callback(doms[i], i);
        }
    }
};
/**
 * @param {Element} element
 * @param {String} type
 * @param {Event} handler
 * @description 添加监听
 * */
tool.addHandler = function (element, type, handler) {
    if (element.addEventListener) {
        element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + type, handler);
    } else {
        element["on" + type] = handler;
    }
};
/**
 * @description 得到浏览器
 * */
tool.myBrowser = function () {
    let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    let ua = {};
    let isOpera = userAgent.indexOf("Opera") > -1;
    //判断是否Opera浏览器
    ua.isOpera = isOpera;
    //判断是否Firefox浏览器
    let isFirefox = userAgent.indexOf("Firefox") > -1;
    ua.isFirefox = isFirefox;
    //判断是否Chrome浏览器
    let isChrome = userAgent.indexOf("Chrome") > -1;
    ua.isChrome = isChrome;
    //判断是否Safari浏览器
    let isSafari = userAgent.indexOf("Safari") > -1;
    ua.isSafari = isSafari;
    if (isChrome === isSafari) {
        ua.isSafari = false;
    }
    let isIE = false;
    let isIE_1_10 = false;
    let IEVersion = -1;
    let isEdge = false;
    let isIE11 = false;
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        isIE = true;
        isIE_1_10 = true;
        //判断是IE几
        let browser = navigator.appName;
        let b_version = navigator.appVersion;
        let version = b_version.split(';');
        let IENAME = "Microsoft Internet Explorer";

        let trim_Version = version[1].replace(/[ ]/g, "");

        if (IENAME === browser && trim_Version === "MSIE6.0") IEVersion = 6;
        else if (IENAME === browser && trim_Version === "MSIE7.0") IEVersion = 7;
        else if (IENAME === browser && trim_Version === "MSIE8.0") IEVersion = 8;
        else if (IENAME === browser && trim_Version === "MSIE9.0") IEVersion = 9;
        else IEVersion = 10;
        // return "IE";
    } //判断是否IE浏览器
    if (!!window.ActiveXObject || 'ActiveXObject' in window) {
        let _isEdge = userAgent.indexOf('Edge') > -1 && !isIE;
        let _isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
        isEdge = _isEdge;
        isIE11 = _isIE11;
        isIE = true;
        if (isIE11) IEVersion = 11;
    }
    ua.isIE = isIE;
    ua.isIE_1_10 = isIE_1_10;
    ua.IEVersion = IEVersion;
    ua.isEdge = isEdge;
    ua.isIE11 = isIE11;
    ua.appType = 'browser';
    let userA = userAgent.toLocaleLowerCase();
    let a = userA.match(/Alipay/i);
    let b = userA.match(/MicroMessenger/i);
    if (a&& a[0] === 'alipay')
        ua.appType = 'alipay';
    else if (b && b[0] === 'micromessenger')
        ua.appType = 'micromessenger';
    return ua;
};

tool.open = function (obj) {
    let path = obj.path || '';
    let param = obj.param || {};

    let arr = [];
    for (let key in param) {
        let val = param[key] ? param[key] : "";
        arr.push(key + '=' + val);
    }
    let query = arr.join('&');
    let url = location.origin + '/#' + path + '?' + query;
    window.open(url)
};
tool.urlCommon = function () {
    let fx_uid = tool.getPar('fx_uid');
    if (fx_uid === '') {
        fx_uid = tool.getCookie('fx_uid');
        if (!fx_uid || fx_uid === 'null' || typeof(fx_uid) === 'undefined' || fx_uid === '') fx_uid = 0;
    } else {
        tool.setCookie('fx_uid', fx_uid, 'h12');
    }
    return {
        fx_uid
    }
};
tool.urlCommon();
tool.$router = {};
tool.$router.push = function (vm, param) {
    let urlParam = tool.urlCommon();
    if (!param.hasOwnProperty('query')) param.query = {};
    param.query = Object.assign(param.query, urlParam);
    tool.log(param.query.URLQueryString());
    tool.log(vm.$router)
    if(param.name === 'order_pay'){
        goPayUrl();
    }else{
        vm.$router.push(param);
    }
    function goPayUrl(){
        let origin = window.location.origin;
        let pathname = window.location.pathname;
        let hash = '?#/main/pay/order_pay?'+param.query.URLQueryString();
        let url = origin+pathname+hash;
        window.location.href = url;
    }
};
tool.$router.replace = function(vm, param){
    let urlParam = tool.urlCommon();
    if (!param.hasOwnProperty('query')) param.query = {};
    param.query = Object.assign(param.query, urlParam);
    if(param.name === 'order_pay'){
        goPayUrl();
    }else{
        vm.$router.replace(param);
    }
    function goPayUrl(){
        let origin = window.location.origin;
        let hash = '/?#/main/pay/order_pay?'+param.query.URLQueryString();
        window.location.href = origin+hash;
    }
};

tool.addClass = function (obj, cls) {
    let obj_class = obj.className;//获取 class 内容.
    let blank = (obj_class !== '') ? ' ' : '';//判断获取到的 class 是否为空, 如果不为空在前面加个'空格'.
    added = obj_class + blank + cls;//组合原来的 class 和需要添加的 class.
    obj.className = added;//替换原来的 class.
};
tool.removeClass = function (obj, cls) {
    let obj_class = ' ' + obj.className + ' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc    bcd' -> ' abc    bcd '
    obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc    bcd ' -> ' abc bcd '
    let removed = obj_class.replace(' ' + cls + ' ', ' ');//在原来的 class 替换掉首尾加了空格的 class. ex) ' abc bcd ' -> 'bcd '
    removed = removed.replace(/(^\s+)|(\s+$)/g, '');//去掉首尾空格. ex) 'bcd ' -> 'bcd'
    obj.className = removed;//替换原来的 class.
};
tool.hasClass = function (obj, cls) {
    let obj_class = obj.className;//获取 class 内容.
    let obj_class_lst = obj_class.split(/\s+/);//通过split空字符将cls转换成数组.
    x = 0;
    for (x in obj_class_lst) {
        if (obj_class_lst[x] === cls) {//循环数组, 判断是否包含cls
            return true;
        }
    }
    return false;
};

export default tool;
